package org.wjw.udp;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UDPEchoClient {
    // 声明一个Socket对象
    private DatagramSocket socket;
    private String serverIp;
    private int serverPort;

    // 通过构造方法来初始化socket, 指定IP地址，端口
    public UDPEchoClient(String serverIp,int serverPort) throws SocketException {
        // 1. 初始化socket
        this.socket = new DatagramSocket();
        // 2. 指定IP地址，端口
        this.serverIp = serverIp;
        this.serverPort = serverPort;

    }

    //启动客户端服务
    public void start() throws IOException {
        System.out.println("客户端服务已启动");
        //循环处理客户端的输入
        while (true){
            System.out.println("->");
            //定义Scanner
            Scanner scanner = new Scanner(System.in);
            //1.获取用户输入
            String request = scanner.nextLine();
            if (request == null || request.isEmpty()){
                System.out.println("您输入了一个空数据");
                continue;
            }

            //2.创建SocketAddress对象，表示服务器的IP和端口
            SocketAddress address = new InetSocketAddress(serverIp, serverPort);
            //3.用户的输入打包成一个DatagramPacket
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),
                    request.getBytes().length,address);

            //4.发送数据到服务器
            socket.send(requestPacket);
            //5.接受服务器响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePacket);
            //6.解析得到的响应数据
            String response = new String(responsePacket.getData(),0,responsePacket.getLength(),StandardCharsets.UTF_8);
            //7.打印响应日志
            System.out.printf("request = %s, response = %s\n",request,response);
        }

    }

    public static void main(String[] args) throws IOException {
        UDPEchoClient udpEchoClient = new UDPEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }


}
